package com.xcyy.clbzbh.controller;

import com.xcyy.clbzbh.VO.ResultVO;
import com.xcyy.clbzbh.common.ResultVOUtil;
import com.xcyy.clbzbh.entity.Report;
import com.xcyy.clbzbh.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class ReportController {

    @Autowired
    private ReportService reportService;
    @Value("${uploadPath}")
    String realPath;

    @PostMapping("/uploadreport")
    public ResultVO uploadReport(Report report, @RequestParam(value = "file" ,required = false)MultipartFile file) throws IOException {

        File folder = new File(realPath + "report");
        if (!folder.isDirectory()) {
            folder.mkdirs();
        }
        if (file!=null){
            // 获取文件名
            String name = file.getOriginalFilename();
            //判断是否为IE浏览器的文件名，IE浏览器下文件名会带有盘符信息
            // Check for Unix-style path
            int unixSep = name.lastIndexOf('/');
            // Check for Windows-style path
            int winSep = name.lastIndexOf('\\');
            // Cut off at latest possible point
            int pos = (winSep > unixSep ? winSep : unixSep);
            if (pos != -1) {
                // Any sort of path separator found...
                name = name.substring(pos + 1);
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            name = uuid + name.substring(name.lastIndexOf("."));
            file.transferTo(new File(folder, name));
            report.setPic("/report/"+name);
        }
        Report result=reportService.save(report);
        return ResultVOUtil.success(report);
    }
}
